<template>
  <div style="width: 26%;margin:0 auto">
    <a-form :model="state" @finish="onFinish" v-bind="formItemLayout">
      <a-form-item label="文献名字" v-bind="validateInfos.name">
        <a-input v-model:value="state.name"/>
      </a-form-item>

      <a-form-item label="文献作者" v-bind="validateInfos.author">
        <a-input v-model:value="state.author"/>
      </a-form-item>

      <a-form-item label="出版社" v-bind="validateInfos.press">
        <a-input v-model:value="state.press"/>
      </a-form-item>

      <a-form-item label="简介" v-bind="validateInfos.introduce">
        <a-textarea v-model:value="state.introduce" :rows="4"/>
      </a-form-item>

      <a-form-item label="附件" v-bind="validateInfos.file_id">
        <a-upload
            v-model:file-list="fileList"
            name="file"
            accept=".pdf,.mp3,.mp4"
            :action="BASE_UPLOAD_FILE"
            @change="handleChange"
        >
          <div v-if="fileList.length<1">
            <a-button>
              <UploadOutlined/>
              上传附件
            </a-button>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item label="上传封面" v-bind="validateInfos.cover_id">
        <a-upload
            accept="image/*"
            v-model:file-list="coverList"
            :action="BASE_UPLOAD_FILE"
            list-type="picture-card"
            @preview="handlePreview"
        >
          <div v-if="coverList.length < 1">
            <PlusOutlined/>
            <div style="margin-top: 8px">上传</div>
          </div>
        </a-upload>
      </a-form-item>

      <!-- 编号 -->
      <a-form-item label="编号" v-bind="validateInfos.code">
        <a-input-number v-model:value="state.code" :min="0"/>
      </a-form-item>

      <!-- 分类 -->
      <CategoryFrom :id="route.params.id"
                    :validate-infos="validateInfos"
                    :state="state"
                    :type-id="detailData?.dict?.type_id??''"/>

      <a-form-item :wrapper-col="{ offset: 9 }">
        <a-button type="primary" html-type="submit">提交</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>

    <!--  预览图片  -->
    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script setup lang="ts">

import {onMounted, reactive, ref} from "vue";
import {useForm} from "ant-design-vue/es/form";
import type {UploadChangeParam, UploadProps} from 'ant-design-vue';
import {getBase64} from "@/util";
import {PlusOutlined, UploadOutlined} from '@ant-design/icons-vue';
import {message} from "ant-design-vue";
import {useRoute, useRouter} from "vue-router";
import type {AxiosResponse} from "axios";
import CategoryFrom from "@/components/CategoryFrom.vue";
import {BASE_UPLOAD_FILE} from "@/axios";
import type {LiteratureDataType, LiteratureFormType} from "@/util/publicType";
import {createdLiterature, literatureDetail, updateLiterature} from "@/api/api";

let state = reactive<LiteratureFormType>({
  name: '',
  author: '',
  press: "",
  introduce: "",
  file_id: "",
  cover_id: "",
  code: 0,
  category_id: ''
});
// 参数获取
const route = useRoute();
// 是否预览
const previewVisible = ref(false);
// 预览地址
const previewImage = ref('');
// 预览标题
const previewTitle = ref('');
// 附件list
const fileList = ref<any>([]);
// 封面list
const coverList = ref<any>([]);
// 详情
const detailData = ref<LiteratureDataType | null>(null);
// 是否为更新页面
const isUpdate = route.path.indexOf("update") >= 0;
// 跳转
const router = useRouter();

// 请求
onMounted(() => {
  if (isUpdate) {
    literatureDetail((route.params.id as string)).then((r: AxiosResponse) => {
      const {data} = r.data.data;
      detailData.value = data;
      state = Object.assign(state, {
        name: data.name,
        author: data.author,
        press: data.press,
        introduce: data.introduce,
        code: data.code,
        category_id: data.category_id
      });
      const cover: any = {
        uid: data?.cover?.id,
        status: 'done',
        name: data?.cover?.type,
        url: data?.cover?.path
      };
      const file: any = {
        uid: data?.file?.id,
        status: 'done',
        name: data?.file?.type,
        url: data?.file?.path
      }
      coverList.value = [cover];
      fileList.value = [file];
    }, err => message.error(err))
  }
});
// 表单布局
const formItemLayout = {
  labelCol: {
    sm: {span: 5},
  },
  wrapperCol: {
    sm: {span: 16},
  },
};

// form参数设定
const ruleRef = reactive({
  name: [
    {
      required: true,
      message: "请输入名称"
    }
  ],
  author: [
    {
      required: false
    }
  ],
  press: [
    {
      required: false
    }
  ],
  introduce: [
    {
      required: false
    }
  ],
  cover_id: [
    {
      required: false,
      message: "请上传封面"
    }
  ],
  file_id: [
    {
      required: false,
      message: "请上传附件"
    }
  ],
  category_id: [
    {
      required: true,
      message: "请选择分类"
    }
  ],
  code: [
    {
      required: false
    }
  ]
});

// 获取参数表单事件
const {resetFields, validate, validateInfos} = useForm(state, ruleRef);

// 取消预览
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

// 预览操作
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  // 转换格式
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  // 预览地址
  previewImage.value = file.url || file.preview;
  // 预览显示
  previewVisible.value = true;
  // 预览名字
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

// 上传附件
const handleChange = (info: UploadChangeParam) => {
  // 上传中
  if (info.file.status !== 'uploading') {
    // console.log(info.file, info.fileList);
  }
  // 上传成功
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 上传成功`);
  } else if (info.file.status === 'error') {
    // 上传失败
    // message.error(`${info.file.name} file upload failed.`);
  }
};


// 表单完成
const onFinish = () => {
  let request: Promise<AxiosResponse>;
  validate().then(() => {
    const file_id = fileList.value[0]?.response?.data?.data?.id;
    const cover_id = coverList.value[0]?.response?.data?.data?.id;
    state.file_id = file_id ? file_id : fileList.value[0]?.uid;
    state.cover_id = cover_id ? cover_id : coverList.value[0]?.uid;
    if (!state.file_id) {
      return message.error("请上传附件");
    }
    if (!state.cover_id) {
      return message.error("请上传封面");
    }
    if (isUpdate) {
      request = updateLiterature((route.params.id as string), state);
    } else {
      request = createdLiterature(state);
    }
    request.then(() => {
      // 清除数据
      resetFields();
      // 清除文件数据
      coverList.value = [];
      fileList.value = [];
      // 更新页面返回上一页
      if (isUpdate) {
        router.push(`/literature/${detailData.value?.category_id}`)
      }
      detailData.value = null;
      message.success("操作成功");
    }, err => message.error(err))
  })
}
</script>